import { showMsg } from "./msg"
import { Local, Session } from "./storage"
import { TOKEN_KEY, REFRESH_ACCESS_TOKEN_KEY, RequestHttpIntervalEnum } from "@/const"

export const clearToken = () => {
    Local.remove(TOKEN_KEY)
    Local.remove(REFRESH_ACCESS_TOKEN_KEY)
    Session.clear()
}

export const findParentPath = (menuList: any[], targetId: number): number[] => {
    const path: number[] = []
    const find = (list: any[], id: number): boolean => {
        for (const item of list) {
            if (item.id === id) {
                path.push(item.id)
                return true
            }
            if (item.children?.length) {
                if (find(item.children, id)) {
                    path.unshift(item.id)
                    return true
                }
            }
        }
        return false
    }
    find(menuList, targetId)
    return path
}

/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength = 10) => {
    return 'id_' + Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
}



/**
 * * 处理请求事件单位
 * @param num 时间间隔
 * @param unit RequestHttpIntervalEnum
 * @return number 秒数
 */
export const intervalUnitHandle = (num: number, unit: RequestHttpIntervalEnum) => {
    switch (unit) {
        // 秒
        case RequestHttpIntervalEnum.SECOND:
            return num * 1000
        // 分
        case RequestHttpIntervalEnum.MINUTE:
            return num * 1000 * 60
        // 时
        case RequestHttpIntervalEnum.HOUR:
            return num * 1000 * 60 * 60
        // 天
        case RequestHttpIntervalEnum.DAY:
            return num * 1000 * 60 * 60 * 24
        default:
            return num * 1000
    }
}

// 判断是否为图表预览
export const isPreview = ()=>{
    return location.href.includes('preview')
}

const isString = (val:any)=>typeof val === 'string'
const isFun = (val:any)=>typeof val === 'function'

const prefix = 'javascript:'
// 字符串转换处理
export const translateStr = (target:string | Record<any,any>)=>{
    if(isString(target)){
        if(target.startsWith(prefix)){
            const funStr = target.split(prefix)[1] // 去除前缀
            let result 
            try {
                result = new Function(`${funStr}`)()
                console.log(result);
            } catch (error) {
                console.log(error);
                showMsg('js内容解析有误','error')
            }
            return result
        }else {
            return target
        }
    }
    for (const key in target) {
        if(Object.prototype.hasOwnProperty.call(target,key)){
            const subTarget = target[key] //取值
            target[key] = translateStr(subTarget)
        }
    }
    return target
}

